//
// Created by pengx on 2025/11/19.
//

#ifndef GB28181_RTP_SENDER_HPP
#define GB28181_RTP_SENDER_HPP

#include <cstdint>
#include <vector>
#include <netinet/in.h>
#include <sdp_parser.hpp>

class RtpSender {
public:
    explicit RtpSender() = default;

    static RtpSender *getSender() {
        static RtpSender instance;
        return &instance;
    }

    RtpSender(const RtpSender &) = delete;

    RtpSender &operator=(const RtpSender &) = delete;

    bool initRtpSocket(SdpStruct &sdp);

    void initSpsPps(const uint8_t *sps, size_t sps_len, const uint8_t *pps, size_t pps_len);

    /**
     * @param h264 每一帧画面的 H.264 NALU 数据。已经处理过PPS和SPS参数
     * */
    void pushVideoFrame(const uint8_t *h264, size_t h264_length, uint64_t pts_90khz,
                        bool is_key_frame);

    /**
     * @param alaw pcm编码后的 G.711A 数据
     * */
    void pushAudioFrame(const uint8_t *alaw, size_t alaw_length, uint64_t pts_90khz);

    ~RtpSender();

private:
    int _rtp_socket = -1;                   // 用于发送数据的socket
    struct sockaddr_in _remote_addr{};      // 远程平台地址信息
    uint32_t _ssrc = 0x12345678;
    uint8_t _payload_type = 96;
    std::vector<uint8_t> _sps{};
    std::vector<uint8_t> _pps{};
    std::atomic<uint16_t> _seq{0}; // RTP 序列号

    void buildPsPacket(const uint8_t *payload, size_t len, uint64_t pts_90khz, bool is_video,
                       bool is_key_frame);

    void sendRtpPacket(const uint8_t *payload, size_t len, uint64_t timestamp, bool marker);
};


#endif //GB28181_RTP_SENDER_HPP
